package org.budo.dubbo.protocol.http.dispatcher;

import java.io.ByteArrayInputStream;
import java.util.Map;

import org.budo.dubbo.protocol.http.BudoDubboHttpProtocol;
import org.budo.dubbo.protocol.http.invocation.BudoDubboRpcInvocation;
import org.budo.dubbo.protocol.http.invocation.adapter.InvocationAdapter;
import org.budo.dubbo.protocol.http.invocation.adapter.ProtocolRequest;
import org.budo.dubbo.protocol.http.invocation.adapter.ProtocolResponse;
import org.budo.dubbo.protocol.http.invocation.adapter.impl.ProtocolRequestInvocationAdapter;
import org.budo.support.lang.util.MapUtil;

import com.alibaba.dubbo.rpc.Exporter;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.fastjson.JSON;

/**
 * websocket 在用
 * 
 * @author li
 */
public class DispatcherSupport {
    public BudoDubboRpcInvocation adaptInvocation(InvocationAdapter invocationAdapter, ProtocolRequest protocolRequest) {
        try {
            return invocationAdapter.adaptInvocation(protocolRequest);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

    public Exporter<?> findInterfaceExporter(BudoDubboRpcInvocation invocation, BudoDubboHttpProtocol protocol) {
        String interfaceName = invocation.getInterfaceName();

        if (null == protocol || null == interfaceName) {
            return null;
        }

        Map<String, Exporter<?>> exporterMap = protocol.getExporterMap();
        if (null == exporterMap) {
            return null;
        }

        return exporterMap.get(interfaceName);
    }

    public InvocationAdapter getInvocationAdapter() {
        return new ProtocolRequestInvocationAdapter();
    }

    public void renderInvokeResult(ProtocolRequest protocolRequest, ProtocolResponse protocolResponse, Result result) {
        Map<String, Object> responseMap = MapUtil.stringObjectMap("requestId", protocolRequest.getRequestId(), //
                "result", MapUtil.stringObjectMap("value", result.getValue(), "exception", result.getException()));

        String responseJson = JSON.toJSONString(responseMap);
        protocolResponse.write(new ByteArrayInputStream(responseJson.getBytes()));
    }
}